package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// RechargeRecordController 充值记录控制器
type RechargeRecordController struct {
	web.Controller
}

// List 获取充值记录列表
func (c *RechargeRecordController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取过滤参数
	orderNo := c.GetString("order_no")
	memberId, _ := c.GetInt64("member_id", 0)
	status, _ := c.GetInt8("status", -1)
	startTime, _ := c.GetInt64("start_time", 0)
	endTime, _ := c.GetInt64("end_time", 0)

	// 构建过滤条件
	filters := make(map[string]interface{})
	if orderNo != "" {
		filters["order_no"] = orderNo
	}
	if memberId > 0 {
		filters["member_id"] = memberId
	}
	if status != -1 {
		filters["status"] = status
	}
	if startTime > 0 {
		filters["start_time"] = startTime
	}
	if endTime > 0 {
		filters["end_time"] = endTime
	}

	// 加盟商权限过滤
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 获取充值记录列表
	records, total, err := models.GetRechargeRecordList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取充值记录列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"list":  records,
			"total": total,
		},
	}
	c.ServeJSON()
}

// GetOne 获取单个充值记录详情
func (c *RechargeRecordController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的ID参数",
		}
		c.ServeJSON()
		return
	}

	// 获取充值记录详情（使用带加盟商权限验证的方法）
	record, err := models.GetRechargeRecordByIdWithFranchise(id, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取充值记录详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data":    record,
	}
	c.ServeJSON()
}

// GetByOrderNo 根据订单号获取充值记录
func (c *RechargeRecordController) GetByOrderNo() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取订单号参数
	orderNo := c.GetString("order_no")
	if orderNo == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "订单号不能为空",
		}
		c.ServeJSON()
		return
	}

	// 根据订单号获取充值记录（使用带加盟商权限验证的方法）
	record, err := models.GetRechargeRecordByOrderNoWithFranchise(orderNo, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取充值记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data":    record,
	}
	c.ServeJSON()
}

// Create 创建充值记录
func (c *RechargeRecordController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求数据
	var record models.RechargeRecord
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &record)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 设置加盟商ID
	record.FranchiseId = permResult.Admin.FranchiseId

	// 创建充值记录
	id, err := models.CreateRechargeRecord(&record)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建充值记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建充值记录成功",
		"data": map[string]interface{}{
			"id":       id,
			"order_no": record.OrderNo,
		},
	}
	c.ServeJSON()
}

// UpdateStatus 更新充值记录状态
func (c *RechargeRecordController) UpdateStatus() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求数据
	var data struct {
		Id     int64  `json:"id"`
		Status int8   `json:"status"`
		Remark string `json:"remark"`
	}

	err := json.Unmarshal(c.Ctx.Input.RequestBody, &data)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取充值记录（使用带加盟商权限验证的方法）
	record, err := models.GetRechargeRecordByIdWithFranchise(data.Id, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取充值记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 更新状态
	record.Status = data.Status
	record.Description = data.Remark

	// 如果是已支付状态，设置支付时间
	if data.Status == 1 {
		record.PayTime = time.Now().Unix()
	}

	// 更新充值记录
	err = models.UpdateRechargeRecord(record, "Status", "Description", "PayTime")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新充值记录状态失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新充值记录状态成功",
	}
	c.ServeJSON()
}
